package com.ganzi.manager.activiti.listener;

/**
 * @author lxd
 * @create 2019/7/2
 * 驳回到起点   待完善
 */

import org.activiti.bpmn.model.FlowNode;
import org.activiti.bpmn.model.SequenceFlow;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.impl.cmd.NeedsActiveTaskCmd;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntityManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;


public class RollbackFirstTaskCmd extends NeedsActiveTaskCmd<Void> {
    private static Logger logger = LoggerFactory.getLogger(RollbackFirstTaskCmd.class);

    public RollbackFirstTaskCmd(String taskId){
        super(taskId);
    }
    public String deletereason;

    @Override
    public Void execute(CommandContext commandContext, TaskEntity currentTask) {
        String processDefinitionId = currentTask.getProcessDefinitionId();
        String executionId = currentTask.getExecutionId();//获取任务的执行实例id

        //删除当前任务
        TaskEntityManager taskEntityManager = commandContext.getTaskEntityManager();
        taskEntityManager.deleteTask(currentTask, deletereason, false, false);

        //获取第一个用户节点
        FlowNode firstUserTask = this.findFirstActivity(processDefinitionId);
        ExecutionEntity executionEntity = commandContext.getExecutionEntityManager().findById(executionId);

        // 获取目标节点的来源连线
        List<SequenceFlow> flows = firstUserTask.getIncomingFlows();
        if (flows == null || flows.isEmpty()) {
            throw new ActivitiException("回退错误，目标节点没有来源连线");
        }
        // 随便选一条连线来执行，时当前执行计划为，从连线流转到目标节点，实现跳转
        executionEntity.setCurrentFlowElement(flows.get(0));
        commandContext.getAgenda().planTakeOutgoingSequenceFlowsOperation(executionEntity, true);
        return null;
    }

    @Override
    public String getSuspendedTaskException() {
        return "挂起的任务不能跳转";
    }

    /**
     * 获得第一个用户节点.
     */
    public FlowNode findFirstActivity(String processDefinitionId) {
            return null;
    }
}